package com.kedacom.demo.cometd;

import org.cometd.bayeux.Message;
import org.cometd.bayeux.client.ClientSessionChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * (用一句话描述类的主要功能)
 * @author huangchunhua
 * @date 2016年4月25日
 */
@Component
public class CometdMessageConsumer implements ApplicationListener<ContextRefreshedEvent> {

	private static Logger logger = LoggerFactory.getLogger(CometdMessageConsumer.class);

	private static ClientSessionChannel.MessageListener messageConsumerListener = null;

	/**
	 * 监听cometd消息
	 */
	public static class MessageConsumerListener implements ClientSessionChannel.MessageListener {

		@Override
		public void onMessage(ClientSessionChannel channel, Message message) {
			// 如果传递的消息是String，则message.getData是String；
			// 如果传递的消息是对象（会被序列化成JSON），message.getData将返回LinkedHashMap
			logger.debug("Receive message: {}", message.getData());
		}
	}

	/*
	 * (non-Javadoc)
	 * @see
	 * org.springframework.context.ApplicationListener#onApplicationEvent(org
	 * .springframework.context.ApplicationEvent)
	 */
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if (event.getApplicationContext().getParent() == null) {
			messageConsumerListener = new MessageConsumerListener();
			CometdJavaClient.getBayeuxClient().getChannel("/demo").subscribe(messageConsumerListener);
		}

	}

}
